package edu.cmu.cs211.snake.gui;

import java.awt.Point;
import java.util.Collections;
import java.util.Random;
import java.util.Set;

import edu.cmu.cs211.snake.util.MyHashSet;

public class FoodManager {

	private Random rand = new Random ();

	private Game game;

	private Set <Point> foodLocations = new MyHashSet <Point> ();

	private static final int INITIAL_FOOD = 3;

	private static final int ADD_FOOD_FACTOR = 10;

	public FoodManager (Game g) {
		game = g;
		for (int i = 0; i < INITIAL_FOOD; i++)
			addFood ();
	}

	/**
	 * Tries to eat food
	 * 
	 * @param p
	 *            The point at which to eat food
	 * @return true if food was eaten.
	 */
	public boolean tryEat (Point p)
	{
		return foodLocations.remove (p);
	}

	public void tick ()
	{
		if (foodLocations.size () < INITIAL_FOOD
		        || rand.nextInt (foodLocations.size () * ADD_FOOD_FACTOR) == 0)
			addFood ();
	}

	public Set<Point> getFoodLocations ()
	{
		return Collections.unmodifiableSet (foodLocations);
	}

	private boolean isGoodFoodLocation (Point p)
	{
		if (foodLocations.contains (p))
			return false;
		if (game.getSnake ().getPoints ().contains (p))
			return false;
		return true;
	}

	private void addFood ()
	{
		Point p;

		do {
			p = new Point (rand.nextInt (game.getSize ().width), rand
			        .nextInt (game.getSize ().height));
		} while (!isGoodFoodLocation (p));

		foodLocations.add (p);
	}
}
